package com.yanfan.data.tdengine.service.factory;

import com.yanfan.data.mapper.SnmpResponseMapper;
import com.yanfan.data.tdengine.config.SnmpTDengineConfig;
import com.yanfan.data.tdengine.dao.TDSnmpResponseDao;
import com.yanfan.data.tdengine.service.TDSnmpResponseService;
import com.yanfan.data.tdengine.service.impl.MySqlSnmpResponseServiceImpl;
import com.yanfan.data.tdengine.service.impl.TDSnmpResponseServiceImpl;
import com.yanfan.framework.config.MyBatisConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.lang.Nullable;
import org.springframework.stereotype.Component;

@Component
public class SnmpResponseServiceFactory {

    @Autowired
    private ApplicationContext applicationContext;


    @Bean
    public TDSnmpResponseService getSnmpResponseService() {
        //先获取TDengine的配置，检测TDengine是否已经配置
        if (containBean(SnmpTDengineConfig.class)) {
            SnmpTDengineConfig tDengineConfig = applicationContext.getBean(SnmpTDengineConfig.class);
            TDSnmpResponseDao tdSnmpResponseDao = applicationContext.getBean(TDSnmpResponseDao.class);
            TDSnmpResponseService SnmpResponseService = new TDSnmpResponseServiceImpl(tDengineConfig, tdSnmpResponseDao);
            return SnmpResponseService;
        } else if (containBean(MyBatisConfig.class)) {
            //没有配置TDengine，那么使用MySQL的日志配置
            SnmpResponseMapper snmpResponseMapper = applicationContext.getBean(SnmpResponseMapper.class);
            TDSnmpResponseService SnmpResponseService = new MySqlSnmpResponseServiceImpl(snmpResponseMapper);
            return SnmpResponseService;
        } else {
            return null;
        }
    }

    /**
     * @return
     * @Method containBean
     * @Description 根据类判断是否有对应bean
     * @Param 类
     * @date 2022/5/22,0022 14:12
     * @author wxy
     */

    private boolean containBean(@Nullable Class<?> T) {
        String[] beans = applicationContext.getBeanNamesForType(T);
        return beans != null && beans.length != 0;
    }
}
